import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

import '../../models/models.dart';
import '../../repositories/repositories.dart';

part 'articles_event.dart';
part 'articles_state.dart';

const _itemsPerRequest = 20;

class ArticlesBloc extends Bloc<ArticlesEvent, ArticlesState> {
  final ArticleRepository articleRepository;
  ArticlesBloc({
    required this.articleRepository
  }) : super(ArticlesInitial()) {
    on<LoadArticlesEvent>((event, emit) async {
      emit(ArticlesLoading());
      try{
        var files = await articleRepository.getArticles( event.tag, event.author, event.favorited, _itemsPerRequest , 0);
        emit(ArticlesLoaded(feedType: FeedType.globalFeed, articles:  files, hasReachedMax:  false ));
      } catch (e){
        emit(ArticlesError(error: e));
      }  
    }
    );
    on<UpdateArticleInListEvent>((event, emit) async {
      emit(ArticlesLoading());
      try{
        var files= await articleRepository.getArticles( event.article.slug, event.article.author.userId, event.article.favorited, _itemsPerRequest , 0);
        emit(ArticlesLoaded(feedType: FeedType.globalFeed, articles:  files, hasReachedMax:  false ));
      } catch (e){
        emit(ArticlesError(error: e));
      }  
    }
    );
    on<ReloadArticlesEvent>((event, emit) async {
      emit(ArticlesLoading());
      try{
        var files = await articleRepository.getArticles( event.article.slug, event.article.author.userId, event.article.favorited, _itemsPerRequest , 0);
        emit(ArticlesLoaded(feedType: FeedType.globalFeed, articles:  files, hasReachedMax:  false ));
      } catch (e){
        emit(ArticlesError(error: e));
      }  
    }
    );
    on<LoadArticlesFeedEvent>((event, emit) async {
      emit(ArticlesLoading());
      try{
        var files = await articleRepository.getArticles( event.tag, event.author, event.favorited, _itemsPerRequest , 0);
        emit(ArticlesLoaded(feedType: FeedType.globalFeed, articles:  files, hasReachedMax:  false ));
      } catch (e){
        emit(ArticlesError(error: e));
      }  
    }
    );
  }
}
